<template>
  <div class="stock-details">
    <h2>股票详情</h2>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else-if="stock">
      <div class="stock-info">
        <h3>{{ stock.name }} ({{ stock.symbol }})</h3>
        <p>当前价格: ¥{{ stock.currentPrice.toFixed(2) }}</p>
        <div class="actions">
          <el-button @click="simulatePriceChange" type="primary">模拟价格变动</el-button>
          <el-button @click="buyStock" type="success">买入</el-button>
          <el-button @click="sellStock" type="danger">卖出</el-button>
        </div>
      </div>
      
      <div class="trade-form" v-if="showTradeForm">
        <h3>{{ tradeAction }}股票</h3>
        <el-form @submit.prevent="executeTrade" label-width="80px">
          <el-form-item label="数量:">
            <el-input-number 
              v-model="tradeData.quantity" 
              :min="1"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="价格:">
            <el-input-number 
              v-model="tradeData.price" 
              :step="0.01"
              :min="0.01"
              controls-position="right"
            />
          </el-form-item>
          <div class="form-actions">
            <el-button type="primary" @click="executeTrade">执行交易</el-button>
            <el-button @click="cancelTrade">取消</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import apiService from '../services/ApiService';

const route = useRoute();
const stock = ref(null);
const loading = ref(false);
const error = ref(null);
const showTradeForm = ref(false);
const tradeAction = ref('买入');
const tradeData = ref({
  quantity: 1,
  price: 0
});

onMounted(async () => {
  await fetchStockDetails();
});

const fetchStockDetails = async () => {
  try {
    loading.value = true;
    error.value = null;
    const symbol = route.params.symbol;
    
    // 验证股票代码
    const validation = apiService.validateStockSymbol(symbol);
    if (!validation.isValid) {
      error.value = validation.error;
      loading.value = false;
      return;
    }
    
    const response = await apiService.getStockBySymbol(symbol);
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '获取股票详情失败';
    } else {
      stock.value = response;
      tradeData.value.price = response.currentPrice;
    }
  } catch (err) {
    error.value = err.message || '网络错误，请稍后重试';
    console.error('获取股票详情失败:', err);
  } finally {
    loading.value = false;
  }
};

const simulatePriceChange = async () => {
  try {
    await apiService.simulatePriceChanges();
    // 重新获取股票详情以显示更新后的价格
    await fetchStockDetails();
  } catch (err) {
    error.value = '模拟价格变动失败';
    console.error('模拟价格变动失败:', err);
  }
};

const buyStock = () => {
  tradeAction.value = '买入';
  showTradeForm.value = true;
};

const sellStock = () => {
  tradeAction.value = '卖出';
  showTradeForm.value = true;
};

const executeTrade = async () => {
  try {
    const tradeInfo = {
      symbol: stock.value.symbol,
      type: tradeAction.value === '买入' ? 'BUY' : 'SELL',
      quantity: tradeData.value.quantity,
      price: tradeData.value.price
    };
    
    const response = await apiService.createTrade(tradeInfo);
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '交易失败';
    } else {
      ElMessage.success(`${tradeAction.value}成功！`);
      showTradeForm.value = false;
    }
  } catch (err) {
    error.value = '交易执行失败';
    console.error('交易执行失败:', err);
  }
};

const cancelTrade = () => {
  showTradeForm.value = false;
};
</script>

<style scoped>
.stock-details {
  padding: 20px;
}

.loading, .error {
  text-align: center;
  padding: 20px;
}

.error {
  color: red;
}

.stock-info {
  margin-bottom: 20px;
}

.actions {
  margin-top: 20px;
}

.trade-form {
  border: 1px solid #ddd;
  padding: 20px;
  border-radius: 4px;
  margin-top: 20px;
}

.form-actions {
  margin-top: 20px;
}
</style>